package com.pet.serve.controller;

import com.pet.serve.entity.Invest;
import com.pet.serve.response.ApiResponse;
import com.pet.serve.request.ApprovalRequest;
import com.pet.serve.service.InvestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/invest")
public class InvestController {

    private final InvestService investService;

    @Autowired
    public InvestController(InvestService investService) {
        this.investService = investService;
    }

    @PostMapping("/add")
    public ResponseEntity<ApiResponse> addInvest(@RequestBody Invest invest) {
        invest.setTime(new Date()); // 设置当前时间为充值时间
        invest.setStatus(Invest.InvestStatus.no); // 默认状态为待审核
        investService.addInvest(invest); // 调用服务层方法保存充值记录
        return ResponseEntity.ok(new ApiResponse(true, null));
    }

    @GetMapping("/getall")
    public ResponseEntity<ApiResponse> getAllInvests(
            @RequestParam(defaultValue = "1") int page_no,
            @RequestParam(defaultValue = "10") int page_size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String approval, // 新增审批账号参数
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date starttime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endtime,
            @RequestParam(required = false) String status) { // status 为可选参数

        // 记录分页查询
        Page<Invest> investPage;
        if (status == null) {
            investPage = investService.findAllInvestsWithPagination(page_no, page_size, username, approval, starttime, endtime);
        } else {
            try {
                Invest.InvestStatus investStatus = Invest.InvestStatus.valueOf(status.toUpperCase());
                investPage = investService.findInvestsByStatusWithPagination(investStatus, page_no, page_size, username, approval, starttime, endtime);
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().body(new ApiResponse(false, "Invalid invest status: " + status, null, 0));
            }
        }

        ApiResponse response = new ApiResponse(true, "充值记录获取成功", investPage.getContent(), investPage.getTotalElements());
        return ResponseEntity.ok(response);
    }

    // 批量或单个同意充值申请
    @PostMapping("/agree")
    public ResponseEntity<ApiResponse> agree(@RequestBody List<ApprovalRequest> requests) {
        for (ApprovalRequest request : requests) {
            boolean result = investService.approveInvestment(request.getInvestid(), request.getApproval(), request.getMoney());
            if (!result) {
                return ResponseEntity.badRequest().body(new ApiResponse(false, "Failed to approve investment with ID: " + request.getInvestid(), null, 0));
            }
        }
        return ResponseEntity.ok(new ApiResponse(true, "Investments approved successfully", null, 0));
    }

    // 批量或单个拒绝充值申请
    @PostMapping("/refuse")
    public ResponseEntity<ApiResponse> refuse(@RequestBody List<ApprovalRequest> requests) {
        for (ApprovalRequest request : requests) {
            boolean result = investService.refuseInvestment(request.getInvestid(), request.getApproval());
            if (!result) {
                return ResponseEntity.badRequest().body(new ApiResponse(false, "Failed to refuse investment with ID: " + request.getInvestid(), null, 0));
            }
        }
        return ResponseEntity.ok(new ApiResponse(true, "Investments refused successfully", null, 0));
    }


    // 根据用户名获取充值记录
    @GetMapping("/byUsername")
    public ResponseEntity<List<Invest>> getInvestsByUsername(@RequestParam String username) {
        List<Invest> invests = investService.getInvestsByUsername(username);
        return ResponseEntity.ok(invests);
    }

    // 根据状态获取充值记录
    @GetMapping("/byStatus")
    public ResponseEntity<List<Invest>> getInvestsByStatus(@RequestParam Invest.InvestStatus status) {
        List<Invest> invests = investService.getInvestsByStatus(status);
        return ResponseEntity.ok(invests);
    }

    // 根据时间范围获取充值记录
    @GetMapping("/byTimeRange")
    public ResponseEntity<List<Invest>> getInvestsByTimeRange(@RequestParam Date startDate, @RequestParam Date endDate) {
        List<Invest> invests = investService.getInvestsByTimeRange(startDate, endDate);
        return ResponseEntity.ok(invests);
    }

    // 获取所有充值记录
    @GetMapping("/all")
    public ResponseEntity<List<Invest>> getAllInvests() {
        List<Invest> invests = investService.getAllInvests();
        return ResponseEntity.ok(invests);
    }

    // 获取待审批的充值记录
    @GetMapping("/pending")
    public ResponseEntity<List<Invest>> getPendingInvests() {
        List<Invest> invests = investService.getPendingInvests();
        return ResponseEntity.ok(invests);
    }

    // 根据审批账号获取充值记录
    @GetMapping("/byApproval")
    public ResponseEntity<List<Invest>> getInvestsByApproval(@RequestParam String approval) {
        List<Invest> invests = investService.getInvestsByApproval(approval);
        return ResponseEntity.ok(invests);
    }

    // 批量更新充值记录的审批状态
    @PutMapping("/updateStatus")
    public ResponseEntity<Void> updateInvestStatus(@RequestParam List<Long> ids,
                                                   @RequestParam String status,
                                                   @RequestParam String approval) {
        investService.updateInvestStatus(ids, status, approval);
        return ResponseEntity.noContent().build();
    }
}
